<%@page import="com.muapet.model.Pet"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Mua~亲亲宠————编辑宠物信息</title>
<link rel="stylesheet" href="css/style.css" />

<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/bootstrapValidator.css" />
<link rel="stylesheet" href="css/fileinput.min.css" />

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrapValidator.js"></script>
<script type="text/javascript" src="js/fileinput.min.js"></script>
<script type="text/javascript" src="js/fileinput_locale_zh.js"></script>
<script type="text/javascript" src="js/citys.js"></script>


</head>
<body>
	<%@ include file="/WEB-INF/jsp/top.jspf"%>

	<%
		Pet editingPet = (Pet) request.getAttribute("editingPet");
	%>
	<!-- 模态框（Modal） -->
	<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">&times;</button>
					<h4 class="modal-title" id="myModalLabel">提示</h4>
				</div>
				<div class="modal-body"></div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">确定</button>
				</div>
			</div>
		</div>
	</div>
	<div class="title"></div>
	<div class="container  col-sm-offset-2  col-sm-8">
		<div class="panel panel-info">
			<div class="panel-heading">
				<h3 class="panel-title">编辑宠物信息</h3>
			</div>
			<div class="panel-body">
				<div class="col-sm-offset-1  col-sm-9 column">
					<form id="petInfoForm" class="form-horizontal">
						<input type="hidden" id="petId" name="id" value="${editingPet.id}">
						<div class="form-group">
							<label class="col-sm-3 control-label">主题：</label>
							<div class="col-sm-9">
								<input type="text" name="title" class="form-control"
									value="${editingPet.title}" />
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">价格：</label>
							<div class="col-sm-9">
								<input type="text" name="price" class="form-control"
									value="${editingPet.price}" />
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">所在省份：</label>
							<div class="col-sm-9">
								<select class="form-control col-sm-6" name="province"
									id="param_province"
									onchange="provincechange('param_city',this.selectedIndex)"><option>请选择省份</option>
								</select>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">所在城市：</label>
							<div class="col-sm-9">
								<select class="form-control col-sm-6" name="city"
									id="param_city"><option>请选择城市</option>
								</select>
							</div>
						</div>
						<input type="hidden" id="oldProvince"
							value="${editingPet.province}"> <input type="hidden"
							id="oldCity" value="${editingPet.city}">
						<div class="form-group">
							<label class="col-sm-3 control-label">宠物名字：</label>
							<div class="col-sm-9">
								<input type="text" name="name" class="form-control"
									value="${editingPet.name}" />
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">宠物性别：</label>
							<div class="col-sm-9">
								<label class="radio-inline"> <input type="radio"
									name="sex" value="0"
									<%if (editingPet == null || editingPet.getSex() == null
					|| editingPet.getSex() == Pet.PET_SEX_NO) {%>
									checked <%}%>> 未知 </label> <label class="radio-inline">
									<input type="radio" name="sex" value="1"
									<%if (editingPet != null && editingPet.getSex() == Pet.PET_SEX_MALE) {%>
									checked <%}%>> 公 </label> <label class="radio-inline">
									<input type="radio" name="sex" value="2"
									<%if (editingPet != null && editingPet.getSex() == Pet.PET_SEX_FEMALE) {%>
									checked <%}%>> 母 </label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">类别：</label>
							<div class="col-sm-9">
								<label class="radio-inline"> <input type="radio"
									name="type" value="1"
									<%if (editingPet == null || editingPet.getType() == Pet.PET_TYPE_CAT) {%>
									checked <%}%> onclick="loadVarietys()"> 猫 </label> <label
									class="radio-inline"> <input type="radio" name="type"
									value="2"
									<%if (editingPet != null && editingPet.getType() == Pet.PET_TYPE_DOG) {%>
									checked <%}%> onclick="loadVarietys()"> 狗 </label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">品种：</label> <input
								id="varietyName" type="hidden" value="${editingPet.variety}" />
							<div class="col-sm-9" id="pet_varietys"></div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">颜色：</label>
							<div class="col-sm-9">
								<input type="text" name="color" class="form-control"
									value="${editingPet.color}" />
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">详细描述：</label>
							<div class="col-sm-9">
								<div class="textarea">
									<textarea class="form-control" rows="5" name="description">${editingPet.description}</textarea>
								</div>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-6 control-label">宠物图片：最多可上传五张</label>
							<div class="col-sm-6">
								<input type="hidden" id="icon" name="icon"
									value="${editingPet.icon}"> <input type="hidden"
									id="images" name="images" value="${editingPet.images}">
								<div id="uploadfile">
									<input id="iconFile" name="userIcon" type="file"
										style="height: 160px" />
								</div>
							</div>
						</div>
						<div class="form-group" id="showImages"></div>
						<div class="col-sm-offset-2 col-sm-8">
							<button type="button" class="btn btn-info col-sm-offset-2"
								onclick="checkAndSubmit()">确认信息</button>
							<button onclick="javascript:history.go(-1);"
								class="btn btn-info col-sm-offset-2 ">取消</button>
						</div>
					</form>

				</div>
			</div>
		</div>
	</div>

	<script>
		$(document).ready(
				function() {
					initCitys('param_province', 'param_city', $('#oldProvince')
							.val(), $('#oldCity').val());
					loadVarietys();
					loadImages();
					initFileInput("iconFile",
							"http://localhost:8080/muapet/pet/saveImage.do");
					$('#petInfoForm').bootstrapValidator({
						message : 'This value is not valid',
						excluded : [ ':disabled' ],
						feedbackIcons : {
							valid : 'glyphicon glyphicon-ok',
							invalid : 'glyphicon glyphicon-remove',
							validating : 'glyphicon glyphicon-refresh'
						},
						fields : {
							title : {
								message : '',
								validators : {
									notEmpty : {
										message : '主题不能为空'
									},
									stringLength : {
										min : 2,
										max : 50,
										message : '主题最少2个字，最多50字'
									}
								}
							},
							price : {
								message : '',
								validators : {
									notEmpty : {
										message : '价格不能为空，可以为零'
									},
									regexp : {//正则验证  
										regexp : /^[0-9]*(\.\d{1,2})?$/,
										message : '请输入正确定价,可精确到小数点后两位'
									}
								}
							},
							province : {
								message : '',
								validators : {
									notEmpty : {
										message : '省份不能为空'
									},
									callback : {
										message : '必须选择一个省份',
										callback : function(value, validator) {

											if (value == '请选择省份') {
												return false;
											} else {
												return true;
											}

										}
									}
								}
							},
							type : {
								message : '',
								validators : {
									notEmpty : {
										message : '类型必选'
									}
								}
							},
							variety : {
								message : '',
								validators : {
									notEmpty : {
										message : '品种必选'
									}
								}
							},
							color : {
								message : '',
								validators : {
									regexp : {//正则验证  
										regexp : /^[\u4e00-\u9fa5]+$/,
										message : '颜色只能由中文组成'
									}
								}
							}
						}
					});
				});
		function checkAndSubmit() {
			$("#petInfoForm").bootstrapValidator('validate');//提交验证  
			if ($("#petInfoForm").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码  
				$.ajax({
					url : "pet/addPet.do",
					data : $("#petInfoForm").serialize(),
					type : "POST",
					success : function(result) {
						//请求成功时
						if (result.msg == 'success') {
							var id = $("#petId").val();
							$(".modal-body").html("修改宠物成功，点击确定前往宠物详情页");
							if (result.petId != null) {
								var id = result.petId;
								$(".modal-body").html("新增宠物成功，点击确定前往宠物详情页");
							}
							$("#myModal").modal("show");
							$("#myModal").on('hidden.bs.modal', function() {
								var gotoURL = "pet/showPetDetail.do?id=" + id;
								window.location.href = gotoURL;
							});
						} else if (result.msg == 'error') {
							$(".modal-body").html(result.errorMsg);
							$("#myModal").modal("show");
						}
					},
					error : function() {
						//请求失败时
						$(".modal-body").html("提交宠物信息失败");
						$("#myModal").modal("show");
					}

				});
			}
		}

		function loadVarietys() {
			var type = $("#petInfoForm input[name='type']:checked ").val();
			$
					.ajax({
						url : "pet/listVarietysByType.do",
						data : {
							type : type
						},
						success : function(result) {
							console.log(result);
							if (result.msg == 'success') {
								var list = result.varietyList;
								var innerText = "";
								for ( var no in list) {
									innerText = innerText
											+ " <label class='radio-inline'> <input type='radio' name='variety' value=\""
											+ list[no].varietyName + "\"";
									if ($('#varietyName').val() == ""
											&& no == 0) {
										innerText = innerText + " checked ";
									}
									if (list[no].varietyName == $(
											'#varietyName').val()) {
										innerText = innerText + " checked ";
									}

									innerText = innerText + ">"
											+ list[no].varietyName
											+ " </label>";
								}
								$("#pet_varietys").html(innerText);
							} else {
								loadVarietysError();
							}
						},
						error : function() {
							loadVarietysError();
						}
					});
		}
		function loadVarietysError() {
			$(".modal-body").html("获取宠物品种失败");
			$("#myModal").modal("show");
			$("#pet_varietys")
					.html(
							"<button type='button' class='btn btn-info' onclick='loadVarietys()'>重新加载</button>");
		}
		function loadImages() {

			var images = $("#images").val();
			var icon = $("#icon").val();
			var innerHtml = "";
			if (icon != "") {
				var imageslist = images.split(";");
				if (imageslist.length > 5) {
					$("#uploadfile").hide();
				}
				for ( var i = 0; i < imageslist.length - 1; i++) {
					innerHtml = innerHtml
							+ " <div class='col-sm-4'> <div class='thumbnail'><img style='height: 150px;width: 130px' src='"
											+imageslist[i]+"' class='img-responsive'><div class='caption row'>";
					if (imageslist[i].substr(0, imageslist[i].length) == icon) {
						innerHtml = innerHtml
								+ "<label class='label label-info col-sm-6'>主图</label>";
					} else {
						innerHtml = innerHtml
								+ "<button class='btn btn-sm btn-success col-sm-6' onclick='mainImage("
								+ i + ")'>设为主图</button>";
					}
					innerHtml = innerHtml
							+ "<button class='btn btn-sm btn-success col-sm-offset-1 col-sm-4' onclick='deleteImage("
							+ i + ")'>删除</button></div></div></div>";
				}
			}
			$("#showImages").html(innerHtml);
		}
		function deleteImage(index) {
			var images = $("#images").val();
			var icon = $("#icon").val();
			var imageslist = images.split(";");
			var deleteimage = imageslist[index];
			if (imageslist.length == 1) {
				$("#images").val("");
				$("#icon").val("");

			} else {
				imageslist.splice(index, 1);
				$("#images").val(imageslist.join(";"));
				//删除主图默认第一张主图
				if (icon == deleteimage) {
					$("#icon").val(imageslist[0]);
				}
			}
			$("#uploadfile").show();
			loadImages();
		}
		function mainImage(index) {
			var images = $("#images").val();
			var icon = $("#icon").val();
			var imageslist = images.split(";");
			var mainimage = imageslist[index];
			$("#icon").val(mainimage);
			loadImages();
		}
		function newImage(newIcon) {
			var images = $("#images").val();
			var icon = $("#icon").val();
			$("#images").val(images + newIcon + ";");
			if (icon == "") {
				$("#icon").val(newIcon);
			}
			loadImages();
		}

		function initFileInput(ctrlName, uploadUrl) {

			var control = $('#' + ctrlName);
			control.fileinput({
				language : 'zh', //设置语言
				uploadUrl : uploadUrl, //上传的地址
				autoReplace : true,
				uploadAsync : true,
				allowedFileExtensions : [ 'jpg', 'png' ],//接收的文件后缀
				maxFileCount : 1, //表示允许同时上传的最大文件个数 
				showUpload : false, //是否显示上传按钮
				showRemove : false,
				showCaption : true,
				showPreview : false,//不预览
				dropZoneEnabled : false,
				browseClass : "btn btn-primary", //按钮样式             
				previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
			});

			//选择文件后处理事件
			control.on("filebatchselected", function(event, files) {
				control.fileinput("upload");

			}).on("fileerror", function(event, data) {
			}).on("fileuploaded", function(event, data) {

				if (data.response) {
					newImage(data.response);
				}
			});
		}
	</script>


</body>
</html>

